<template>
  <div class="p-[20px]">
    <el-input
      v-model="input"
      style="width: 150px; margin-bottom: 16px"
      placeholder="搜索"
      :prefix-icon="Search"
      @input="handleInput"
    />
    <!-- 添加 ref 和 current-node-key 绑定默认选中的节点 id -->
    <el-tree
      ref="treeRef"
      :data="treeData"
      :highlight-current="true"
      node-key="id"
      :current-node-key="defaultSelectedId"
      default-expand-all
      @node-click="handleClick"
      v-model="defaultSelectedId"
    >
      <template #default="{ node }">
        <el-icon class="mr-[10px] mt-[2px]" size="16">
          <Message />
        </el-icon>
        <span>{{ node.label }}</span>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineExpose } from "vue";
import { Search, Message } from "@element-plus/icons-vue";
import { getFileLabels } from "@/api/know.js";

const props = defineProps({
  loadData: Function,
});

const input = ref("");
const treeRef = ref(null); // 树组件的 ref 引用
const defaultSelectedId = ref("全部"); // 默认选中节点的 id

// 树结构数据
const treeData = ref();

const handleInput = (e) => {
  if (e) {
    treeData.value = treeData.value.filter((item) => item.label.includes(e));
  } else {
    init();
  }
};

const handleClick = (node) => {
  defaultSelectedId.value = node.id;
  props.loadData({ fileLabel: node.id });
};

const init = () => {
  getFileLabels().then((res) => {
    try {
      const d = res.data.labels.filter((item) => item != null);
      treeData.value = d.map((item) => ({ id: item, label: item }));
      treeData.value = [{ id: "全部", label: "全部" }, ...treeData.value];
    } catch {
      treeData.value = [{ id: "全部", label: "全部" }];
    }
  });
};

onMounted(() => {
  init();
});

// 重置树结构数据
const reset = () => {
  defaultSelectedId.value = "全部";
  treeRef.value.setCurrentKey(defaultSelectedId.value);

  props.loadData({ fileLabel: "" });
  init();
};

defineExpose({ reset, defaultSelectedId });
</script>
